package com.fw.mediasession.media.mediasession;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.IMediaControllerCallback;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.fw.mediasession.media.bean.BaseBean;
import com.fw.mediasession.media.mediasession.sessionutils.MediaSessionToClientManager;
import com.orhanobut.logger.Logger;
import com.zy.untils.AppExecutors;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import dagger.hilt.android.qualifiers.ApplicationContext;

/**
 * 连接播放服务的
 */
@Singleton
public class MyMediaConnection {
    private String TAG = "MyMediaConnection: ";
    private final MutableLiveData<Boolean> isConnect;
    private final MediaBrowserCompat mediaBrowserCompat;
    private Context context;
    private AppExecutors appExecutors;
    private MediaControllerCompat.TransportControls transportControls;
    private MediaControllerCompat mediaController;
    //多媒体数据
    private MutableLiveData<BaseBean> currentData = new MutableLiveData<>();
    //标题
    private MutableLiveData<String> title = new MutableLiveData<>();
    //播放时间
    private MutableLiveData<Integer> position = new MutableLiveData<>();
    private MutableLiveData<Integer> index = new MutableLiveData<>();

    @Inject
    public MyMediaConnection(@ApplicationContext Context context, AppExecutors appExecutors) {
        isConnect = new MutableLiveData<>(false);
        this.context = context;
        mediaBrowserCompat = new MediaBrowserCompat(context,
                new ComponentName(context, MyMediaBrowserService.class), connectionCallback, null);
        mediaBrowserCompat.connect();
        this.appExecutors = appExecutors;
    }

    private MediaBrowserCompat.ConnectionCallback connectionCallback = new MediaBrowserCompat.ConnectionCallback() {
        @Override
        public void onConnected() {
            Logger.d(TAG + "connect mediaSession success");
            isConnect.postValue(true);
            if (mediaBrowserCompat.isConnected()) {
                String mediaId = mediaBrowserCompat.getRoot();
                mediaBrowserCompat.unsubscribe(mediaId);
                mediaBrowserCompat.subscribe(mediaId, subscriptionCallback);
                mediaController = new MediaControllerCompat(context, mediaBrowserCompat.getSessionToken());
                mediaController.registerCallback(callback);
                transportControls = mediaController.getTransportControls();
            }
        }

        @Override
        public void onConnectionSuspended() {
            Logger.d(TAG + "connect mediaSession failed");
            isConnect.postValue(false);
        }

        @Override
        public void onConnectionFailed() {
            Logger.d(TAG + "connect mediaSession failed");
            isConnect.postValue(false);
        }
    };
    MediaBrowserCompat.SubscriptionCallback subscriptionCallback = new MediaBrowserCompat.SubscriptionCallback() {
        @Override
        public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {
            super.onChildrenLoaded(parentId, children);
            //返回加载的数据列表
            Logger.d(TAG + "数据：onChildrenLoaded parentId: " + parentId + " children" + children);
        }

        @Override
        public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children, @NonNull Bundle options) {
            super.onChildrenLoaded(parentId, children, options);
            Logger.d(TAG + "数据：onChildrenLoaded parentId: " + parentId + " children" + children);
        }

        @Override
        public void onError(@NonNull String parentId) {
            super.onError(parentId);
        }

        @Override
        public void onError(@NonNull String parentId, @NonNull Bundle options) {
            super.onError(parentId, options);
        }
    };

    MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
        @Override
        public void onSessionReady() {
            Logger.d(TAG + "播放控制：onSessionReady");
        }

        @Override
        public void onSessionDestroyed() {
            Logger.d(TAG + "播放控制：onSessionDestroyed");

        }

        @Override
        public void onSessionEvent(String event, Bundle extras) {
            Logger.d(TAG + "播放控制：onSessionEvent" + event + " Bundle" + extras.toString());
        }

        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            Logger.d(TAG + "播放控制：onPlaybackStateChanged" + state);

        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            Logger.d(TAG + "播放控制：onMetadataChanged MediaMetadataCompat: " + metadata);
            BaseBean bean = MediaSessionToClientManager.getBaseBeanFromMediaMetadataCompat(metadata);
            currentData.setValue(bean);

            title.setValue("标题：" + bean.title + ",专辑:" + bean.album + ",歌手：" + bean.artist);
        }

        @Override
        public void onQueueChanged(List<MediaSessionCompat.QueueItem> queue) {
            Logger.d(TAG + "播放控制：onQueueChanged QueueItem: " + queue);
        }

        @Override
        public void onQueueTitleChanged(CharSequence title) {
            Logger.d(TAG + "播放控制：onQueueTitleChanged title: " + title);
        }

        @Override
        public void onExtrasChanged(Bundle extras) {

            int aLong = extras.getInt(MediaSessionConstants.CURRENT_POSITION);
//            Logger.d(TAG+"播放控制：onExtrasChanged aLong: "+aLong);
            position.setValue(aLong);

            int i = extras.getInt(MediaSessionConstants.CURRENT_INDEX,-1);
            if(i>=0){
                Logger.d(TAG+"当前播放位置 "+i);

                index.setValue(i);
            }
        }

        @Override
        public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
            Logger.d(TAG + "播放控制：onAudioInfoChanged info: " + info);
        }

        @Override
        public void onCaptioningEnabledChanged(boolean enabled) {
            Logger.d(TAG + "播放控制：onCaptioningEnabledChanged enabled: " + enabled);
        }

        @Override
        public void onRepeatModeChanged(int repeatMode) {
            Logger.d(TAG + "播放控制：onRepeatModeChanged repeatMode: " + repeatMode);
        }

        @Override
        public void onShuffleModeChanged(int shuffleMode) {
            Logger.d(TAG + "播放控制：onShuffleModeChanged shuffleMode: " + shuffleMode);
        }

        @SuppressLint("RestrictedApi")
        @Override
        public IMediaControllerCallback getIControllerCallback() {
            Logger.d(TAG + "播放控制：IMediaControllerCallback ");
            return super.getIControllerCallback();
        }

        @Override
        public void binderDied() {
            Logger.d(TAG + "播放控制：binderDied ");
        }
    };

    //点击播放整个列表
    public void playList(ArrayList<? extends BaseBean> medias, int index, int type) {
        if (isMediaSessionReady() && medias != null && medias.size() > index) {

            Bundle bundle = new Bundle();
            bundle.putSerializable(MediaSessionConstants.QUEUE_LIST, medias);
            bundle.putInt(MediaSessionConstants.QUEUE_TYPE, type);
            transportControls.playFromMediaId(medias.get(index).ID, bundle);
//            transportControls.sendCustomAction();
        } else {
            Logger.d("连接失败！或者数据为空");
        }
    }

    public void play() {
        transportControls.play();
    }

    public void pause() {
        transportControls.pause();
    }

    public void skipToNext() {
        transportControls.skipToNext();
    }

    public void skipToPrevious() {
        transportControls.skipToPrevious();
    }

    public void seekTo(Long l) {
        transportControls.seekTo(l);
    }
    int i=2;
    //2全部循环
    // 1单曲循环//
    // 3//随机播放
    public void nextMode() {
        i++;
        if(i>3)i=1;
        if (isMediaSessionReady()) {
            if (i  == PlaybackStateCompat.REPEAT_MODE_ONE) {
                //单曲循环1->全部循环
                transportControls.setRepeatMode(PlaybackStateCompat.REPEAT_MODE_ALL);
            } else if (i == PlaybackStateCompat.REPEAT_MODE_ALL) {
                //全部循环2->随机播放
                transportControls.setRepeatMode(PlaybackStateCompat.SHUFFLE_MODE_ALL + PlaybackStateCompat.SHUFFLE_MODE_GROUP);
            } else if (i == PlaybackStateCompat.SHUFFLE_MODE_ALL + PlaybackStateCompat.SHUFFLE_MODE_GROUP) {
                //随机播放3->单曲循环
                transportControls.setRepeatMode(PlaybackStateCompat.REPEAT_MODE_ONE);
            }
        }


    }


    /**
     * MediaSession会话是否准备好
     */
    private Boolean isMediaSessionReady() {
        return mediaBrowserCompat.isConnected() && mediaController.isSessionReady();
    }


    /****************************data***********************/
    public MutableLiveData<BaseBean> getCurrentData() {
        return currentData;
    }

    public MutableLiveData<String> getTitle() {
        return title;
    }

    public MutableLiveData<Integer> getPosition() {
        return position;
    }


}
